package me.magicall.web.simple.spring.controllers;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import me.magicall.db.model.BaseModel.MapModel;
import me.magicall.db.model.BaseModel.MapModel.LongIdMapModel;
import me.magicall.db.outsea.springjdbc.Add;
import me.magicall.db.util.DbUtil;
import me.magicall.web.simple.spring.util.C;
import me.magicall.web.simple.spring.util.U;
import me.magicall.web.simple.spring.util.UrlPatternRule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping(method = RequestMethod.POST, //
value = { UrlPatternRule.SINGULAR_MODEL_NAME,//
})
@Controller("updateController")
public class UpdateController {

	@Autowired
	private Add<MapModel<?>> add;

	//add
	@RequestMapping({ "/{op:update}", "/update", "/update/" })
	public String update(final HttpServletRequest request, final ModelMap modelMap,//
			@PathVariable("modelName") final String modelName) {
		update(request, modelMap, modelName, 0);
		return U.redirect("/" + modelName + "/edit");
	}

	@SuppressWarnings("unchecked")
	@RequestMapping({ UrlPatternRule.ID, UrlPatternRule.ID + "/update" })
	public String update(final HttpServletRequest request, final ModelMap modelMap,//
			@PathVariable("modelName") final String modelName,//
			@PathVariable("id") final long id) {
		final Map<String, Object> finalParamMap = (Map<String, Object>) request.getAttribute(C.REQUEST_PARAMS_NAME);
		if (id != 0) {
			modelMap.addAttribute(DbUtil.COMMON_ID_FIELD_NAME, id);
			finalParamMap.put(DbUtil.COMMON_ID_FIELD_NAME, id);
		}

		U.addOrUpdate(modelName, add, new LongIdMapModel(finalParamMap));

		modelMap.addAttribute("modelName", modelName);
		return id == 0 ? U.forward("/" + modelName + "/edit") : U.redirect("/" + modelName + "/" + id);
	}
}
